<template>
    <div id="userList">
        <div class="row wrapper border-bottom white-bg page-heading m-b-md">
            <div class="col-lg-10">
                <h2> 系统管理</h2>
                <el-breadcrumb separator="/">
                    <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
                    <el-breadcrumb-item>系统管理</el-breadcrumb-item>
                    <el-breadcrumb-item>用户列表</el-breadcrumb-item>
                </el-breadcrumb>
            </div>
        </div>

        <div class="wrapper wrapper-content animated fadeInRight">
            <div class="row">
                <div class="col-lg-12">
                    <div class="ibox-title page-content-header">
                        <h5>用户列表</h5>
                        <div class="ibox-tools m-t-n-xs" @click="showAddUserModal">
                            <a class="btn btn-xxs btn-danger"> 新增用户 </a>
                        </div>
                    </div>
                </div>
            </div>

            <div class="row m-b">
                <div class="col-lg-12">
                    <div class="ibox-content clearfix">
                        <div class="row">
                            <div class="col-md-1 text-center">
                                <label class="col-form-label m-r" for="name">用户名</label>
                            </div>
                            <div class="col-md-11">
                                <div class="input-group m-b">
                                    <input type="text" class="form-control" id="name" name="name" v-model="searchParam.userName" placeholder="请输入用户名" />
                                    <div class="input-group-append" @click="getUserList({ pageNo: 1 })">
                                        <span class="input-group-addon">搜索</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <el-table class="no-border" stripe :data="userList" style="width: 100%">
                            <el-table-column prop="userName" label="用户名">
                            </el-table-column>
                            <el-table-column prop="fullName" label="姓名">
                            </el-table-column>
                            <el-table-column prop="phone" label="手机">
                            </el-table-column>
                            <el-table-column prop="staffCode" label="工号">
                            </el-table-column>
                            <el-table-column prop="companyName" label="所属公司">
                            </el-table-column>
                            <el-table-column prop="roleName" label="权限信息">
                            </el-table-column>
                            <el-table-column prop="lastLoginTime" label="最后登录时间">
                                <template slot-scope="scope">
                                    <span>{{scope.row.lastLoginTime|moment("YYYY-MM-DD HH:mm")}}</span>
                                </template>
                            </el-table-column>
                            <el-table-column prop="username" label="" width="100">
                                <template slot-scope="scope">
                                    <div class="btn-group btn-group-toggle" data-toggle="buttons">
                                        <div class="btn btn-white btn-xxs">
                                            <a class="" @click="showEditModal(scope.row)"> 编辑 </a>
                                        </div>
                                        <div class="btn btn-white btn-xxs" @click="deleteUser(scope.row)">
                                            <a href="#" > 删除 </a>
                                        </div>
                                    </div>
                                </template>
                            </el-table-column>
                        </el-table>
                        <div class="pagination">
                            <el-pagination background layout="prev, pager, next" :current-page.sync="pagination.currentPage" :page-size="pagination.size" :total="pagination.total" @current-change="handleCurrentChange">
                            </el-pagination>
                        </div>
                    </div>
                </div>
            </div>

        </div>

        <el-dialog title="新增用户" :visible.sync="addUser.dialogVisible" class="edit-user">
            <el-form :model="addUser.form" ref="addUser.form" :rules="userRules">
                <el-form-item label="登录名" :label-width="formLabelWidth" prop="userName">
                    <el-input v-model="addUser.form.userName" autoComplete="off" placeholder="请输入系统登录名"></el-input>
                </el-form-item>
                <el-form-item label="密码" :label-width="formLabelWidth" prop="passWord">
                    <el-input v-model="addUser.form.passWord"  autoComplete="off" placeholder="请输入密码"></el-input>
                </el-form-item>
                <el-form-item label="确认密码" :label-width="formLabelWidth" prop="surePassword">
                    <el-input v-model="addUser.form.surePassword" autoComplete="off" placeholder="请再次输入密码"></el-input>
                </el-form-item>
                <el-form-item label="姓名" :label-width="formLabelWidth" prop="fullName">
                    <el-input v-model="addUser.form.fullName" autoComplete="off" placeholder="请输入真实姓名"></el-input>
                </el-form-item>
                <el-form-item label="手机号" :label-width="formLabelWidth" prop="phone">
                    <el-input v-model="addUser.form.phone" type="number" maxlength="11" autoComplete="off" placeholder="请输入手机号"></el-input>
                </el-form-item>
                <el-form-item label="所属公司" :label-width="formLabelWidth" prop="companyCode">
                    <el-select v-model="addUser.form.companyCode" placeholder="请选择所属公司" >
                        <el-option :label="item.companyName" :value='item.companyCode'  v-for='(item,index) in data.companyName' :keys="index"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="权限信息" :label-width="formLabelWidth" prop="roleId">
                    <el-select v-model="addUser.form.roleId"  placeholder="选择角色权限" >
                        <el-option  :label="item.roleName" :value="item.roleId" v-for="item in data.roleType" ></el-option>                        
                    </el-select>
                </el-form-item>
                <el-form-item label="工号" :label-width="formLabelWidth" prop="staffCode">
                    <el-input v-model="addUser.form.staffCode" type="number" maxlength="11" autoComplete="off" placeholder="请输入工号"></el-input>
                </el-form-item>
              
               
            </el-form>
             <div slot="footer" class="dialog-footer">
                <el-button type="danger" @click="saveNewRole('addUser.form')">保存</el-button>
            </div>
        </el-dialog>

        <el-dialog title="编辑信息" :visible.sync="editUser.dialogVisible" class="edit-user">
            <el-form :model="editUser.form" :rules="userRules">
               <el-form-item label="登录名" :label-width="formLabelWidth" prop="userName">
                    <el-input v-model="editUser.form.userName" :disabled='true' autoComplete="off" placeholder="请输入系统登录名"></el-input>
                </el-form-item>
                <el-form-item label="密码" :label-width="formLabelWidth" prop="passWord">
                    <div   @click='resetPassword' class="color-orange">重置密码</div>
                </el-form-item>
                <el-form-item label="姓名" :label-width="formLabelWidth" prop="fullName">
                    <el-input v-model="editUser.form.fullName" autoComplete="off" placeholder="请输入真实姓名"></el-input>
                </el-form-item>
                <el-form-item label="手机号" :label-width="formLabelWidth" prop="phone">
                    <el-input maxlength="11" type="number" v-model="editUser.form.phone" autoComplete="off" placeholder="请输入手机号"></el-input>
                </el-form-item>
                <el-form-item label="所属公司" :label-width="formLabelWidth" prop="companyCode">
                    <el-select v-model="editUser.form.companyCode" placeholder="请选择所属公司" >
                        <el-option :label="item.companyName" :value='item.companyCode' v-for='(item,index) in data.companyName' :key="index"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="权限信息" :label-width="formLabelWidth" prop="roleId">
                    <el-select v-model="editUser.form.roleId"  placeholder="选择角色权限" >
                        <el-option  :label="item.roleName" :value="item.roleId" v-for="item in data.roleType" ></el-option>                        
                    </el-select>
                </el-form-item>
                <el-form-item label="工号" :label-width="formLabelWidth" prop="staffCode">
                    <el-input  type="number" v-model="editUser.form.staffCode" autoComplete="off" placeholder="请输入工号"></el-input>
                </el-form-item>

                
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="danger" @click="saveNewRole('editUser.form')">保存</el-button>
            </div>
              
        </el-dialog>

       
    </div>

</template>

<script>
import { User ,FileManagement } from "@/assets/js/api";
import { getCookie } from "@/assets/js/cookie";
export default {
  name: "userList",
  data() {
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.addUser.form.passWord) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      searchParam: {
        userName: ""
      },
        companyName: [],
      editUser: {
        dialogVisible: false,
        form: {
          userName: "",
          passWord: "",
          fullName: "",
          phone: "",
          staffCode:"",
            companyCode: "",
          roleId: ""
        }
      },
      addUser: {
        dialogVisible: false,
        form: {
          userName: "",
          passWord: "",
          surePassword: "",
          fullName: "",
          phone: "",
          staffCode:"",
            companyCode: "",
          roleId: "",
          roleDesigner:[],
          companyName:[],
        }
      },
      editUserRole: {
        dialogVisible: false
      },
      editState:'',
      userRules: {
        userName: [{ required: true, message: "不能为空", trigger: "blur" }],
        passWord: [{ required: true, message: "不能为空", trigger: "blur" }],
        surePassword: [{ required: true, message: "不能为空", trigger: "blur" },{ validator: validatePass2, trigger: "blur" }],
        fullName: [{ required: true, message: "不能为空", trigger: "blur" }],
        phone: [{ required: true, message: "不能为空", trigger: "blur" }],
        staffCode: [{ required: true, message: "不能为空", trigger: "blur" }],
          companyCode: [{ required: true, message: "不能为空", trigger: "blur" }],
        roleId: [{ required: true, message: "不能为空", trigger: "blur" }],
        roleDesigner:[{ required: true, message: "不能为空", trigger: "blur" }]
      },
      formLabelWidth: "120px",
      userList: [],
      pagination: {
        currentPage: 1,
        size: 10,
        total: 0
      },
      editData: {},
      showRole: false,
      activeRoleContent: [],
      roleData: [
        {
          name: "系统管理员",
          listShow: true,
          radio:"1",
          list: [
            {
              name: "系统管理员01",
              checked:"1",
              menus: [
                {
                  menu: "1"
                },
                {
                  menu: "2"
                },
                {
                  menu: "3"
                },
                {
                  menu: "4"
                }
              ]
            },
            {
              name: "系统管理员02",
              checked:"1",
              menus: [
                {
                  menu: "1"
                },
                {
                  menu: "2"
                }
              ]
            }
          ]
        },
        {
          name: "系统操作员",
          listShow: false,
          list: [
            {
              name: "系统操作员01",
              menus: [
                {
                  menu: "1"
                },
                {
                  menu: "2"
                },
                {
                  menu: "3"
                },
                {
                  menu: "4"
                }
              ]
            },
            {
              name: "系统操作员02",
              menus: [
                {
                  menu: "1"
                },
                {
                  menu: "2"
                }
              ]
            }
          ]
        }
      ],
      data:{}
    };
  },
  created() {
    this.getBasicData();
  },
  mounted() {},

  methods: {
    getBasicData(){

       FileManagement.getThirdPartySearch().then(response=>{
           debugger
        this.data.companyName = response.data;
      
      })
      let params = new FormData();
      params.append('pageNum',1);
      params.append('clientId','batfront');
      params.append('pageSize', this.pagination.size);
      User.getRoleList(params).then(response=>{
        this.data.roleType = response.data;
         this.getUserList({ pageNo: 1 });
      })
    },
    handleCurrentChange(val) {
      console.log(val)
      this.getUserList({ pageNo: val });
    },
    getUserList({ pageNo }) {
      let userId = getCookie('operatorId')
      User.getUserList({ 
          userName : this.searchParam.userName || null,
          pageNumber : pageNo || null, 
          clientId:'batfront',
          pageSize: this.pagination.size || null, })
        .then(response => {

          if (response && response.meta.code === "200") {
            this.userList = response.data.map(item=>{
              return this.filterTableRow(item)
            });
            this.pagination.currentPage = pageNo;
            this.pagination.total = response.meta.total;
          }
        })
      
      
    },
   
    showAddUserModal() {
      this.addUser.dialogVisible = true;
      this.editState = 'new';
     
    },
    handleAddUser() {
      this.addUser.dialogVisible = false;
    },
    showEditModal(dataList) {
      console.log(dataList)
      let tempData = {
        ...dataList,
      }
      this.editUser.dialogVisible = true;
      this.editUser.form = tempData;
      this.editState = 'saved'
     
    },
    handleEditUser() {
      this.editUser.dialogVisible = false;
    },
    changeRoleType(data) {
      this.roleData.map(item => {
        item.listShow = false;
      });
      data.listShow = !data.listShow;
    },
    saveNewRole:_.debounce(function(fromName){
      let params = {}
      if(this.editState == 'new'){
        params = {
            userName: this.addUser.form.userName,
            passWord: this.addUser.form.passWord,
            fullName: this.addUser.form.fullName,
            phone: this.addUser.form.phone,
            staffCode: this.addUser.form.staffCode,
            companyCode: this.addUser.form.companyCode,
            roleId: this.addUser.form.roleId,
            userId: this.addUser.form.userId,
            clientId:"batfront"
        }
        this.$refs[fromName].validate((valid) => {
          
          if (valid) {
            User.createUser(params).then(response=>{
              this.addUser.dialogVisible = false;
              this.addUser.form=[];
              this.editUser.dialogVisible = false;
              this.getUserList({ pageNo: 1 });
            })
          } else {
            console.log('error submit!!');
          
          }
        });
      
      }else if(this.editState =='saved'){
          params = {
            userName: this.editUser.form.userName,
            passWord: this.editUser.form.passWord,
            fullName: this.editUser.form.fullName,
            phone: this.editUser.form.phone,
            staffCode: this.editUser.form.staffCode,
              companyCode: this.editUser.form.companyCode,
            roleId: this.editUser.form.roleId,
            userId: this.editUser.form.userId,
            clientId:"batfront"
        }
        User.createUser(params).then(response=>{
              this.addUser.dialogVisible = false;
              this.editUser.dialogVisible = false;
              this.getUserList({ pageNo: 1 });
            })
      }
     
    }),
    resetPassword: _.debounce(function() {
      let _this = this;
      let curUserId = getCookie('operatorId')
      let param = new FormData();
      param.append('curUserId',curUserId);
      param.append('userId', this.editUser.form.userId);
      User.resetPassWord(param).then(response =>{
        if(response && response.data ){
          _this.$alert(response.data.message, "提示", {
              confirmButtonText: "确定",
              confirmButtonClass: "confirmButtonClass",
              callback: action => {
                 
              }

            });
        }
      })
        
    }, 500)
    ,
    deleteUser: _.debounce(function(data) {
      let _this = this;
      let callback = function() {
       _this.$confirm('确定删除吗？?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          confirmButtonClass: "confirmButtonClass"
        }).then(() => {
            User.deleteUser({ userId: data.userId }).then(response => {
            if (response && response.data) {
              _this.$alert("删除成功", "提示", {
                confirmButtonText: "确定",
                confirmButtonClass: "confirmButtonClass",
                callback: action => {
                }
              })
            }
            _this.getUserList(_this.pagination.currentPage)
          })
        }).catch(() => {
          _this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      }
      
      callback();
    }, 500),
    filterTableRow(item, dataType) {
      return {
        ...item,

        
      };
    },
   
  }
};
</script>

<style>
.edit-user .el-dialog {
  width: 600px;
}
.edit-user .el-dialog .el-form-item__label,
.edit-user .el-dialog .el-input__inner,
.edit-user .el-dialog .el-form-item__content {
  line-height: 30px;
  height: 30px;
  width: 300px;
}
.user-role-content .left {
  width: 150px;
  border: 1px solid #e5e6e7;
  display: inline-block;
  margin-left: 130px;
  float: left;
}

.user-role-content .right {
  width: 200px;
  border-right: 1px solid #e5e6e7;
  border-top: 1px solid #e5e6e7;
  border-bottom: 1px solid #e5e6e7;
  float: left;
}

.user-role-content .role-type {
  height: 30px;
  line-height: 30px;
  background-color: #e7eaec;
  padding-left: 10px;
  text-align: left;
}

.user-role-content .role-list {
  margin-top: 13px;
  padding-left: 31px;
}

.user-role-content .left .role-list {
  height: 209px;
}

.user-role-content .right .title {
  height: 30px;
  line-height: 30px;
  border-bottom: 1px solid #e5e6e7;
  padding-left: 33px;
}
.el-radio+.el-radio{
  margin-left: 0;
}
.user-role-content .right .role-list {
  height: 239px;
  padding-left: 33px;
}
</style>
